home *** CD-ROM | disk | FTP | other *** search
/ io Programmo 60 / IOPROG_60.ISO / soft / c++ / gsl-1.1.1-setup.exe / {app} / src / randist / binomial.c < prev    next >
Encoding:
C/C++ Source or Header  |  2001-05-14  |  2.0 KB  |  88 lines

  1. /* randist/binomial.c
  2.  * 
  3.  * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough
  4.  * 
  5.  * This program is free software; you can redistribute it and/or modify
  6.  * it under the terms of the GNU General Public License as published by
  7.  * the Free Software Foundation; either version 2 of the License, or (at
  8.  * your option) any later version.
  9.  * 
  10.  * This program is distributed in the hope that it will be useful, but
  11.  * WITHOUT ANY WARRANTY; without even the implied warranty of
  12.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  13.  * General Public License for more details.
  14.  * 
  15.  * You should have received a copy of the GNU General Public License
  16.  * along with this program; if not, write to the Free Software
  17.  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  18.  */
  19.  
  20. #include <config.h>
  21. #include <math.h>
  22. #include <gsl/gsl_rng.h>
  23. #include <gsl/gsl_randist.h>
  24. #include <gsl/gsl_sf_gamma.h>
  25.  
  26. /* The binomial distribution has the form,
  27.  
  28.    prob(k) =  n!/(k!(n-k)!) *  p^k (1-p)^(n-k) for k = 0, 1, ..., n
  29.  
  30.    This is the algorithm from Knuth */
  31.  
  32. unsigned int
  33. gsl_ran_binomial (const gsl_rng * r, double p, unsigned int n)
  34. {
  35.   unsigned int i, a, b, k = 0;
  36.  
  37.   while (n > 10)    /* This parameter is tunable */
  38.     {
  39.       double X;
  40.       a = 1 + (n / 2);
  41.       b = 1 + n - a;
  42.  
  43.       X = gsl_ran_beta (r, (double) a, (double) b);
  44.  
  45.       if (X >= p)
  46.     {
  47.       n = a - 1;
  48.       p /= X;
  49.     }
  50.       else
  51.     {
  52.       k += a;
  53.       n = b - 1;
  54.       p = (p - X) / (1 - X);
  55.     }
  56.     }
  57.  
  58.   for (i = 0; i < n; i++)
  59.     {
  60.       double u = gsl_rng_uniform (r);
  61.       if (u < p)
  62.     k++;
  63.     }
  64.  
  65.   return k;
  66. }
  67.  
  68. double
  69. gsl_ran_binomial_pdf (const unsigned int k, const double p, 
  70.               const unsigned int n)
  71. {
  72.   if (k > n)
  73.     {
  74.       return 0 ;
  75.     }
  76.   else 
  77.     {
  78.       double a = k;
  79.       double b = n - k;
  80.       double P;
  81.       double Cnk = gsl_sf_choose (n, k) ;
  82.  
  83.       P = Cnk * pow (p, a) * pow (1 - p, b);
  84.       
  85.       return P;
  86.     }
  87. }
  88.